package happyloan.core;


import android.util.Log;

import org.greenrobot.eventbus.EventBus;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class EventBusUtil<T> implements Callback<RespBase<T>> {
    private RespEvent<T> respEvent;
    private static EventBusUtil<?> instance;

    public EventBusUtil() {
        respEvent = new RespEvent<T>();
    }

    public void sendEvent4Call(Call<RespBase<T>> call) {
        call.enqueue(this);
    }

    @Override
    public void onResponse(Call<RespBase<T>> call, Response<RespBase<T>> response) {
        respEvent = new RespEvent<T>();
        RespBase<T> baseBean = response.body();
        String url = call.request().url().encodedPath();
        respEvent.setUrl(url);
        if (baseBean != null) {
            if (baseBean.getCode() == 1) {
                respEvent.setCode(RespEvent.Code.SUCCEED);
                respEvent.setAlert(baseBean.getIs_alert() == 1);
                respEvent.setT(baseBean.getData());

            } else {
                respEvent.setServerCode(baseBean.getCode());
                respEvent.setCode(RespEvent.Code.FAILURE);
                respEvent.setAlert(baseBean.getIs_alert() == 1);
                respEvent.setExtra(baseBean.getMsg());
            }
        } else {
            respEvent.setCode(RespEvent.Code.ERROR);
        }
        EventBus.getDefault().post(respEvent);
    }

    @Override
    public void onFailure(Call<RespBase<T>> call, Throwable t) {
        String url = call.request().url().encodedPath();
        respEvent.setCode(RespEvent.Code.ERROR);
        respEvent.setUrl(url);
        EventBus.getDefault().post(respEvent);
    }
}
